
package com.bei_en.teacher.management.controller;

import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.bei_en.teacher.management.model.system.condition.SystemUserCondition;
import com.bei_en.teacher.management.model.system.vo.SystemUserVo;
import com.bei_en.teacher.management.service.system.SystemResourceService;
import com.bei_en.teacher.management.service.system.SystemRoleService;
import com.bei_en.teacher.management.service.system.SystemUserService;
import com.bei_en.teacher.management.shiro.EndecryptUtils;
import com.bei_en.teacher.management.web.MyJsonFailResult;
import com.bei_en.teacher.management.web.MyJsonSuccessResult;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;

@Controller
@RequestMapping("/admin")
public class IndexController extends BaseController {

    @Autowired
    private SystemUserService systemUserService;

    @Autowired
    private SystemResourceService systemResourceService;

//    @Autowired
//    private LoginInfoService loginInfoService;

    @Autowired
    private SystemRoleService systemRoleService;

    @Autowired
    private Producer captchaProducer;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(HttpServletRequest request) {

	request.removeAttribute("error");
	return "/admin/login.jsp";
    }

    @RequestMapping("/logout")
    public String logout() {

	SecurityUtils.getSubject().logout();
	return "redirect:/admin/login";
    }

    @RequestMapping("/denied")
    public String denied() {

	return "/admin/denied.jsp";
    }

    /**
     * 用户登录
     * 认证过程：
     * 1、想要得到Subject对象,访问地址必须跟shiro的拦截地址内,不然会报空指针
     * 2、用户输入的账号和密码,存到UsernamePasswordToken对象中,然后由shiro内部认证对比
     * 3、认证执行者交由ShiroDbRealm中doGetAuthenticationInfo处理
     * 4、当以上认证成功后会向下执行,认证失败会抛出异常
     *
     * @param accountName	账户名称
     * @param password	密码
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String userLogin(@RequestParam("accountName") String accountName, @RequestParam("password") String password, String captcha, boolean remember,
	    HttpServletRequest request, HttpSession session) {

	UsernamePasswordToken token = null;
	try {
	    // 从session中取出servlet生成的验证码text值
	    String expected = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
	   // String expected = captcha;// --
	    // 获取用户页面输入的验证码
	    if (!captcha.equalsIgnoreCase(expected)) {
		request.setAttribute("error", "验证码错误！");
		return "/admin/login.jsp";
	    } else {
		// 想要得到Subject对象,访问地址必须在shiro的拦截地址内,不然会报空指针
		Subject subject = SecurityUtils.getSubject();
		token = new UsernamePasswordToken(accountName, password);
		token.setRememberMe(remember);
		subject.login(token);
		if (subject.isAuthenticated()) {
		    /*   LoginInfoEntity loginInfo = new LoginInfoEntity();
		       Session session = SecurityUtils.getSubject().getSession();
		       loginInfo.setUserId(Integer.valueOf(session.getAttribute("userSessionId")
		        .toString()));
		       loginInfo.setAccountName(accountName);
		       loginInfo.setLoginIp(session.getHost());
		       loginInfoService.insert(loginInfo);*/
		    request.removeAttribute("error");
		} else {
		    token.clear();
		    request.setAttribute("error", "用户名或密码不正确！");
		    return "/admin/login.jsp";
		}
	    }
	} catch (LockedAccountException e) {
	    token.clear();
	    request.setAttribute("error", "用户已经被锁定不能登录，请与管理员联系！");
	    return "/admin/login.jsp";
	} catch (ExcessiveAttemptsException e) {
	    token.clear();
	    request.setAttribute("error", "账号："+accountName+" 登录失败次数过多,锁定10分钟!");
	    return "/admin/login.jsp";
	} catch (AuthenticationException e) {
	    token.clear();
	    request.setAttribute("error", "用户名或密码不正确！");
	    return "/admin/login.jsp";
	} catch (Exception e) {
	//    token.clear();
	    request.setAttribute("error", "登录异常，请联系管理员！");
	    return "/admin/login.jsp";
	}

	session.setAttribute("accountName", accountName);
	session.setAttribute("password", password);

	return "redirect:/admin/index";
    }

    /**
     * 用户注册
     *
     * @param vo
     * @return
     */
//    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register(SystemUserVo vo) {

	try {
	    SystemUserVo user = EndecryptUtils.md5Password(vo.getName(), vo.getPassword(), 2);
	    vo.setPassword(user.getPassword());
	    vo.setSalt(user.getSalt());
	    vo.setWorkNumber(1111);
	    vo.setStatus(1);
	    vo.setUpdateTime(new Date());
//	    RoleEntity roleEntity = roleService.findByName("普通用户");
//	    vo.setRole(roleEntity);
	    systemUserService.insert(vo);
	} catch (Exception e) {
	    e.printStackTrace();
	}
	return "/admin/login.jsp";

    }

    /**
     * 后台修改密码
     * @param oldpassword
     * @param newpassword
     * @param secpassword
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value = "/changepwd", method = RequestMethod.POST)
    public String changepwd(String oldpassword, String newpassword, String secpassword,
	    HttpServletResponse resp, HttpSession session) {

	String password = (String) session.getAttribute("password");
	String accountName = (String) session.getAttribute("accountName");
	if (!newpassword.equals(secpassword)) {
	    writeJson(resp, new MyJsonFailResult("两次输入新密码不一致"));
	    return null;
	}
	if (!oldpassword.equals(password)) {
	    writeJson(resp, new MyJsonFailResult("输入的旧密码不正确"));
	    return null;
	}
	try {

	    SystemUserCondition voC = new SystemUserCondition();
	    SystemUserVo vo = new SystemUserVo();

	    voC.setName(accountName);
	    List<SystemUserVo> sysUser = systemUserService.findSystemUserPage(voC);
	    vo = sysUser.get(0);
	    SystemUserVo user = EndecryptUtils.md5Password(accountName, newpassword, 2);
	    vo.setPassword(user.getPassword());
	    vo.setSalt(user.getSalt());
	    systemUserService.updateSelective(vo);

	} catch (Exception e) {
	    e.printStackTrace();
	    writeJson(resp, new MyJsonFailResult(e.getMessage()));
	    return null;
	}
	MyJsonSuccessResult re = new MyJsonSuccessResult(true);
	writeJson(resp, re);
	return null;
    }
}
